package com.hitqz.robot.driver.netty.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * ip黑名单处理器
 */
@Slf4j
public class IpBlacklistHandler extends ChannelInboundHandlerAdapter {

    private final Set<String> blacklist ;
    private static final Set<String> loggedIps = Collections.synchronizedSet(new HashSet<>());  // 记录已打印日志的 IP

    public IpBlacklistHandler(Set<String> blacklist) {
        this.blacklist = blacklist;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 获取客户端的 IP 地址
        InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = remoteAddress.getAddress().getHostAddress();

        // 检查客户端 IP 是否在黑名单中
        if (blacklist.contains(clientIp)) {
            if (loggedIps.add(clientIp)) {
                log.warn("[track]Client IP {} is blacklisted, closing connection.", clientIp);
            }
            ctx.close();  // 关闭连接
        } else {
            super.channelActive(ctx);  // 继续处理连接
        }
    }
}
